package com.lagou.edu.controller;


import com.lagou.edu.bean.UploadResult;
import com.lagou.edu.service.OssDemoService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Data
@RestController
@RequestMapping("/ossdemo")
public class OssDemoController {
	@Autowired
	private OssDemoService ossDemoService;

	@PostMapping("/upload")
	@ResponseBody
	public UploadResult upload(@RequestParam("file") MultipartFile multipartFile) {
		return ossDemoService.upload(multipartFile);
	}

	@PostMapping("/download")
	@ResponseBody
	public void download(HttpServletResponse response, String fileName) throws IOException {
		byte[] bytes = ossDemoService.download(fileName);
		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		response.setCharacterEncoding("UTF-8");
		ServletOutputStream outputStream = null;

		try {
			outputStream = response.getOutputStream();
			outputStream.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@PostMapping("/delete")
	@ResponseBody
	public UploadResult delete(String fileName) {
		return ossDemoService.delete(fileName);
	}
}


